package com.cross.sax;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.cross.core.AbstractReader;
import com.cross.core.Writer;

public class SimpleSAXReader extends AbstractReader {

	private XMLReader reader = null;
	private InputStreamReader isReader;
	private Reader r;
	public SimpleSAXReader(File file, Writer writer) throws ParserConfigurationException,
			SAXException, IOException {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		SimpleSAXHandler handler = new SimpleSAXHandler(writer);
		reader = parser.getXMLReader();
		reader.setContentHandler(handler);
		InputStream is = new FileInputStream(file);
		InputStreamReader isReader = new InputStreamReader(is, "UTF-8");
		InputSource inputSource = new InputSource(isReader);
		reader.parse(inputSource);
		isReader.close();
		rowIndex = 0;
		header = handler.getHeader();
	}

	public SimpleSAXReader(InputStream is, Writer writer) throws ParserConfigurationException,
			SAXException, IOException {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		SimpleSAXHandler handler = new SimpleSAXHandler(writer);
		reader = parser.getXMLReader();
		reader.setContentHandler(handler);
		isReader = new InputStreamReader(is, "UTF-8");
		InputSource inputSource = new InputSource(isReader);
		reader.parse(inputSource);
		rowIndex = 0;
		header = handler.getHeader();
	}

	public SimpleSAXReader(Reader r, Writer writer) throws ParserConfigurationException,
			SAXException, IOException {
		this.r = r;
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		SimpleSAXHandler handler = new SimpleSAXHandler(writer);
		reader = parser.getXMLReader();
		reader.setContentHandler(handler);
		InputSource inputSource = new InputSource(r);
		reader.parse(inputSource);
		rowIndex = 0;
		header = handler.getHeader();
	}

	@Override
	protected boolean nextRow() {
		return true;
	}

	@Override
	public void close() {
		if(isReader != null){
			try {
				isReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(r != null){
			try {
				r.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
